/*
 * @Author: yangni 920556271@qq.com
 * @Date: 2024-05-09 15:25:26
 * @LastEditors: yangni 920556271@qq.com
 * @LastEditTime: 2024-05-21 14:01:38
 * @FilePath: /yt-devops/lib/pages/devices/device_tab/history_info/history_info_view.dart
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import 'dart:convert';

import 'package:bruno/bruno.dart';
import 'package:dart_date/dart_date.dart';
import 'package:flutter/material.dart';
import 'package:flutter_echarts/flutter_echarts.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:yt_devops/components/app_bar/app_bar_widget.dart';
import 'package:yt_devops/components/card_wrap.dart';
import 'package:yt_devops/components/common_chart.dart';
import 'package:yt_devops/components/gaps.dart';
import 'package:yt_devops/components/tips.dart';
import 'package:yt_devops/model/data_type_config.dart';
import 'package:yt_devops/pages/devices/device_tab/device_detail/new_air_cooling_page/temperature_full_chart/component/full_screen_back.dart';
import 'package:yt_devops/pages/site/site_statis_data/show_full_screen_btn.dart';
import 'package:yt_devops/resources/str_res_keys.dart';
import 'package:yt_devops/styles/styles.dart';
import 'package:yt_devops/utils/constants/time_formated.dart';
import 'package:yt_devops/utils/extensions.dart';
import 'package:yt_devops/utils/func_utils.dart';
import 'history_info_controller.dart';

class HistoryInfoPage extends GetView<HistoryInfoController> {
  const HistoryInfoPage({Key? key}) : super(key: key);

  @override
  HistoryInfoController get controller => Get.put(HistoryInfoController());

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBarWidget.defaultAppBar(controller.tabController.name),
      body: GetBuilder<HistoryInfoController>(
        builder: (controller) => SmartRefresher(
            enablePullDown: true,
            enablePullUp: false,
            controller: controller.refreshController,
            onRefresh: controller.getChartData,
            header: ListTips.classicHeader,
            child: ListView(
              shrinkWrap: true,
              children: [
                CardWrap(
                  padding: EdgeInsets.symmetric(horizontal: 16.w),
                  child: Column(children: [
                    BrnTextSelectFormItem(
                      title: ResKey.deviceDataCollectionPoints.tr,
                      value: controller.dataPoint?['paramName'] ?? '',
                      onTap: () => controller.selectDataPoint(),
                      themeData: BrnFormItemConfig(
                          contentTextStyle: BrnTextStyle(
                              color: Colour.otherTextColor, fontSize: 14.sp)),
                    ),
                    Gaps.line,
                    BrnTextSelectFormItem(
                      title: ResKey.deviceQueryDate.tr,
                      onTap: () =>
                          controller.selectTime(context, controller.date),
                      value:
                          controller.date.format(TimeFormated.dateShowFromated),
                      themeData: BrnFormItemConfig(
                          contentTextStyle: BrnTextStyle(
                              color: Colour.otherTextColor, fontSize: 14.sp)),
                    ),
                    Row(
                      children: [
                        const Spacer(),
                        ShowFullScreenBtn(
                          onTap: toFullScreen,
                        ),
                      ],
                    ),
                    SizedBox(height: 282, child: chart()
                        //  CommonChartWidget(
                        //   isValueType: controller.isYxisTypeIsValue,
                        //   yAxisDataSource: [controller.chartDataSource],
                        //   xAxisDataSource: controller.timeList,
                        // ),
                        ),
                  ]),
                ),
              ],
            )),
      ),
    );
  }

  Widget chart([bool isFullScreen = false]) {
    return Echarts(captureHorizontalGestures: true, option: '''
      { 
        color: ['#007DFF'],
        grid: {
          top: 35,
          bottom: 50,
          right: 30,
          left:15,
          containLabel: true,
        },
        dataZoom: [
        {
          type: 'inside',
          realtime: false,
        },
        ${isFullScreen ? jsonEncode({
                'start': 0,
                'bottom': 40,
                'end': 0,
                'height': 10,
                'realtime': false,
              }) : ''}
        ],
        tooltip: {
          trigger: 'axis',
          backgroundColor: 'rgba(0,0,0,0.85)',
          borderWidth: 0,
          opacity: 0.2,
          confine: true,
          textStyle: {
            color: 'white',
            fontSize:11
          },
          formatter: (params) => {
            const { value, name, marker } = (params || [{}])[0];
            const result = [name];
            result.push(
              `\${marker} ${controller.dataPoint?['paramName'] ?? ''} ${controller.unit(controller.propperty) != null ? '(${controller.unit(controller.propperty)})' : ''}: ` + (value ?? '--')
            );
            return result.join('<br/>');
       
          },
        },
        xAxis: {
          type: 'category',
          axisLine:{
            lineStyle:{
              color:'#E6E6E6'
            }
          },
          axisLabel: {
          color: '#999999',
          fontSize: 11,
          interval: function (index) { // 自定义间隔函数 
              if (index % ${controller.getAxisInterval(controller.timeList)} === 0) { // 每四小时显示一次  // 返回值是五分钟为一个间隔
                  return true;
              } else {
                  return false;
              }
            },
            formatter:function (value, index) {
              return value.substring(11,16)
            },
          },
          data:${jsonEncode(controller.timeList)}
        },
        yAxis: 
             ${controller.propperty?.dataType?.type == DataTypeConfigEnum.enumType ? '''{
              type: 'category',
              interval: 1,
              // axisLabel: {
              //   formatter: (value) => {
              //       return  value == null ? '' : ${jsonEncode(controller.getEnumArray(controller.propperty))}[value];
              //   },
              // },
              // max: ${controller.getEnumArray(controller.propperty).length},
              // min: 0,
              axisTick: {
                alignWithLabel: false
              },
              axisLine:{
                show:true,
                lineStyle: {
                  color:'rgba(0, 0, 0, 0.09)',
                }
              },
              axisLabel: {
                color: '#999999',
                fontSize: 11,
              },
              splitLine:{
                show:true,
                lineStyle:{
                  color:'rgba(0, 0, 0, 0.09)',
                  type:'dashed'
                }
              },
              data:${jsonEncode(controller.getEnumArray(controller.propperty))}
            }''' : '''{
              name:${controller.unit(controller.propperty) != null} ?  '${controller.unit(controller.propperty)}' : undefined,
              nameTextStyle: {
                padding: [0, 0, 5, 20]
              },
              type: 'value',
             
              splitLine:{
                show:true,
                lineStyle:{
                  type:'dashed',
                  color:'rgba(0, 0, 0, 0.09)'
                }
              },
              axisLabel: {
                color: '#999999',
                fontSize: 11,
              },
            }'''},

        
        series: [
          {
            data: ${jsonEncode(controller.dataSourceList)},
            type: 'line',
            smooth: true,
          
          }
        ]
       
      }
      ''');
  }

  toFullScreen() {
    Get.to(
      SafeArea(
        child: RotatedBox(
          quarterTurns: 1,
          child: Scaffold(
            backgroundColor: Colors.white,
            body: Column(children: [
              // Gaps.vGap10,
              FullScreenBack(() {
                navigator?.pop();
              }),
              Expanded(
                child: chart(true),
              )
            ]),
          ),
        ),
      ),
    );
  }
}
